<?php

namespace app\api\controller\store;

use app\api\controller\Controller;
use app\api\model\store\Clerk;
use app\api\model\store\Store as StoreModel;
use app\common\library\easywechat\AppMp;
use app\common\model\shopper\Shopper;
use app\common\model\village\Village as VillageModel;
use app\shop\model\supplier\Supplier;
use app\common\model\product\ProductClaim;

use app\Request;

/**
 * 门店列表
 */
class Store extends Controller
{
    /**
     * 门店列表
     */
    public function lists($longitude = '', $latitude = '', $url = '', $shop_supplier_id = 0)
    {
        $model = new StoreModel;
        $list = $model->getList(true, $longitude, $latitude, false, $shop_supplier_id);
        $signPackage = '';
        if ($url != '') {
            $app = AppMp::getApp($this->app_id);
            $app->jssdk->setUrl($url);
            $signPackage = $app->jssdk->buildConfig(array('getLocation', 'openLocation'), false);
        }
        return $this->renderSuccess('', compact('list', 'signPackage'));
    }

    /**
     * 门店详情
     */
    public function detail($store_id)
    {
        $detail = StoreModel::detail($store_id);
        return $this->renderSuccess('', compact('detail'));
    }

    public function getVillageList(Request $request)
    {
        $params = $request->param();
        $order_id = $params['order_id'] ?? '';
        $Village = new VillageModel;
        $Shopper = new Shopper;
        $ProductClaim = new ProductClaim();
        $Clerk = new Clerk();
        $user = $this->getUser();
        $clerk = Clerk::getByUser($user);
        $store_id = $clerk['store_id'];//门店id
        $Store = new StoreModel;
        $city_id = $Store->where('store_id', $store_id)->value('city_id');//获取当前门店所在的城市id
        $transfer_type = $params['transfer_type'] ?? 1;//（1=店员转给特殊配送员或者店内互转，跨店互转，2=特殊配送员原路转回或者转给同一个小区的人）

        $poptype = $params['poptype'] ?? 0; //0=店内，1=跨店， 2=一秒到家
        if ($poptype == 1) {
            //跨店
            $where = [];
            $where[] = ['store_id', '<>', $store_id];
            $popsearch = $params['popsearch'] ?? '';
            if ($popsearch) {
                $where[] = ['store_name', 'like', '%' . $popsearch . '%'];
            }
            $OurAlist = $Store
                ->where($where)
                ->where(['city_id' => $city_id])
                ->where(['status' => 1])
                ->where(['is_delete' => 0])
                ->where(['check_store' => 1])
                ->field('store_id,status,check_store,store_name,province_id,city_id,region_id')
                ->select()
                ->column('store_id');
            $map = [];
            if ($popsearch) {
                $where = [];
                $where[] = ['store_id', '<>', $store_id];
                $OurAllList = $Store
                    ->where($where)
                    ->where(['city_id' => $city_id])
                    ->where(['status' => 1])
                    ->where(['is_delete' => 0])
                    ->where(['check_store' => 1])
                    ->field('store_id,status,check_store,store_name,province_id,city_id,region_id')
                    ->select()
                    ->column('store_id');
                $map = function ($query) use ($OurAlist, $OurAllList, $popsearch) {
                    $query->whereIn('store_id', $OurAlist?:[0])->whereOr(function ($q) use ($OurAllList, $popsearch) {
                        $q->whereIn('store_id', $OurAllList)->where('real_name|mobile', 'like', '%' . $popsearch . '%');
                    });
                };
            } else {
                $map[] = ['store_id', 'in', $OurAlist];
            }
            $store_list = $Store
                ->where($where)
                ->where(['city_id' => $city_id])
                ->where(['status' => 1])
                ->where(['is_delete' => 0])
                ->where(['check_store' => 1])
                ->column('store_name','store_id');

            $list = $Clerk->where(['is_delete' => 0])
                ->where($map)
                ->where('user_id!=' . $user['user_id'])
                ->select();
            foreach ($list as $key => $value){
                $list[$key]['store_name'] = $store_list[$value['store_id']]??'';

            }
            return $this->renderSuccess('', compact('list'));
        } elseif ($poptype == 2) { //转给一秒到家的配送员

            //一秒到家
            $where = [];
            $map = [];
            $map[] = ['city_id', '=', $city_id];
            $map[] = ['status', '=', 1];
            $popsearch = $params['popsearch'] ?? '';
            if ($popsearch) {
                $map[] = ['name', 'like', '%' . $popsearch . '%'];
            }
            if ($transfer_type == 2) { //一秒到家的只可以转给同一个小区的配送员
                $village_id = $Shopper->where('uid', $user['user_id'])->value('village_id'); //查找小区id
                $where[] = ['a.village_id', '=', $village_id];
                $where[] = ['a.uid', '<>', $user['user_id']];

            } else { //（1=店员转给特殊配送员）
                $villager_ids = $Village->where($map)->column('id');
                $where[] = ['a.village_id', 'in', $villager_ids];
            }
            $where[] = ['a.status', '=', 1];
            $field = 'a.*,v.name';
            $list = $Shopper->alias('a')->join('shop_village v', 'a.village_id = v.id')->where($where)->field($field)->select();
            return $this->renderSuccess('', compact('list'));
        } elseif ($poptype == 0) {

            $store_list = $Store
                ->where(['city_id' => $city_id])
                ->where(['status' => 1])
                ->where(['is_delete' => 0])
                ->where(['check_store' => 1])
                ->where(['store_id' => $store_id])
                ->column('store_name','store_id');
            ;
            //店内
            $popsearch = $params['popsearch'];
            if ($popsearch) {
                $list = $Clerk
                    ->where('real_name|mobile', 'like', '%' . $popsearch . '%')
                    ->where(['store_id' => $store_id])
                    ->where(['is_delete' => 0])
                    ->where('user_id!=' . $user['user_id'])
                    ->select();
            } else {
                $list = $Clerk->where(['store_id' => $store_id])
                    ->where('user_id!=' . $user['user_id'])
                    ->where(['is_delete' => 0])
                    ->select();
            }
            foreach ($list as $key => $value){
                $list[$key]['store_name'] = $store_list[$value['store_id']]??'';
            }
            
            return $this->renderSuccess('', compact('list'));
        }

    }

    /**
     * 判断点是否在范围内
     * @return bool
     * @Author joey
     * @date 2024/3/7 10:09
     */
    public function pointinrange()
    {
        $data = $this->postData();
        $res = false;
        if (empty($data['store_id']) && empty($data['shop_supplier_id'])) {
            return $this->renderError('', ['res' => false]);
        }
        if (!isset($data['coordinates']) || !is_array($data['coordinates'])) {
            return $this->renderError('', ['res' => false]);
        }
        if (array_values($data['coordinates']) !== $data['coordinates']) {
            return $this->renderError('', ['res' => false]);
        }

        if ($data['store_id']) {
            $storeModel = StoreModel::detail($data['store_id']);
            if ($storeModel->isEmpty()) {
                return $this->renderError('', ['res' => false]);
            }
        }
        if ($data['shop_supplier_id']) {
            $storeModel = Supplier::detail($data['shop_supplier_id'], ['store']);
            $storeModel = $storeModel['store'][0];
            if (!$storeModel) {
                return $this->renderError('', ['res' => false]);
            }
        }
        // 坐标点排序，以防前端传递参数格式错误
        if (pointInPolygon(sort($data['coordinates']), $storeModel['scope_coordinates'])) {
            $res = true;
        }

        return $this->renderSuccess('', ['res' => $res]);
    }

}